<template>
  <el-dialog
    v-model="dialogVisible"
    title="批改作业"
    width="80%"
    :before-close="handleClose"
    class="grading-dialog"
  >
    <div class="grading-container">
      <!-- 左侧学生列表 -->
      <div class="student-list">
        <el-table
          :data="submissionList"
          highlight-current-row
        >
          <el-table-column prop="student_id" label="学号" width="100"  />
          <el-table-column prop="student_name" label="姓名"  width="100"/>
          <el-table-column prop="status" label="状态"  width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 'SUBMITTED' && 'success' || 'info'">
                {{ row.status === 'SUBMITTED' && '已提交' || '未提交' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <div class="operation-buttons">
                <el-button
                  v-if="row.status === 'SUBMITTED'"
                  type="primary"
                  size="small"
                  @click.stop="viewSubmission(row)"
                >
                  查看作业
                </el-button>
                <el-button
                  v-if="row.status === 'SUBMITTED'"
                  type="info"
                  size="small"
                  @click.stop="viewPeerReviews(row)"
                >
                  互评记录
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 左下角的互评记录区域 -->
        <div class="peer-reviews-section" v-if="showPeerReviews">
          <h4>互评记录</h4>
          <el-table
            :data="peerReviews"
            style="width: 100%"
            border
            stripe
            v-loading="peerReviewsLoading"
          >
            <el-table-column prop="reviewer" label="评价人">
              <template #default="{ row }">
                <el-tag size="small">{{ row.reviewer }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="score" label="评分" >
              <template #default="{ row }">
                <div class="score-display">
                  <el-rate
                    v-model="row.score"
                    :max="0"
                    disabled
                    show-score
                    text-color="#ff9900"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="feedback" label="评价内容">
              <template #default="{ row }">
                <div class="feedback-content">{{ row.feedback }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" >
              <template #default="{ row }">
                <el-button
                  type="danger"
                  size="small"
                  @click="deletePeerReview(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="peerReviews.length === 0 && !peerReviewsLoading" class="no-data">
            暂无互评记录
          </div>
        </div>
      </div>

      <!-- 右侧作业内容和评分区域 -->
      <div class="submission-detail" v-if="currentSubmissionDetail">
        <div class="submission-header">
          <h3>作业详情</h3>
          <div class="student-info">
            <span>学生：{{ currentSubmissionDetail.student && currentSubmissionDetail.student.username }}</span>
            <span>提交时间：{{ formatDate(currentSubmissionDetail.submitted_at) }}</span>
          </div>
        </div>

        <div class="submission-content">
          <h4>作业内容：</h4>
          <div class="content-text">{{ currentSubmissionDetail.content }}</div>

          <!-- 附件列表 -->
          <div v-if="currentSubmissionDetail.attachments && currentSubmissionDetail.attachments.length" class="attachments">
            <h4>附件：</h4>
            <ul>
              <li v-for="attachment in currentSubmissionDetail.attachments" :key="attachment.id">
                <el-link :href="attachment.file_path" target="_blank" type="primary">
                  下载附件 ({{ formatDate(attachment.uploaded_at) }})
                </el-link>
              </li>
            </ul>
          </div>

          <!-- 评分区域 -->
          <div class="grading-section">
            <h4>评分：</h4>
            <el-form :model="gradingForm" label-width="120px">
              <el-form-item label="教师评分">
                <el-input-number
                  v-model="gradingForm.teacher_score"
                  :min="0"
                  :max="100"
                  :precision="1"
                />
              </el-form-item>
              <el-form-item label="互评权重">
                <el-input-number
                  v-model="gradingForm.peer_weight"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  :precision="1"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitGrade">提交评分</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>

      <!-- 未选择学生时的提示 -->
      <div v-else class="no-selection">
        <el-empty description="请选择要查看的学生作业" />
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const props = defineProps({
  visible: Boolean,
  assignmentId: {
    type: [String, Number],
    required: true
  },
  peerReviewDueDate: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['update:visible', 'graded'])

// 数据状态
const submissionList = ref([{
  submission_id: null,
  student_id: null,
  student_name: null,
  status: null,
  grade: null
}])
const currentSubmissionDetail = ref(null)
const dialogVisible = ref(false)
const currentSubmissionId = ref(null)
const gradingForm = ref({
  teacher_score: 0,
  peer_weight: 0.5
})
const peerReviews = ref([])
const peerReviewsLoading = ref(false)
const showPeerReviews = ref(false)

// 监听visible属性变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    fetchSubmissionStatus()
  }
})

watch(() => dialogVisible.value, (newVal) => {
  emit('update:visible', newVal)
  if (!newVal) {
    resetState()
  }
})

// 重置状态
const resetState = () => {
  currentSubmissionDetail.value = null
  gradingForm.value = {
    teacher_score: 0,
    peer_weight: 0.5
  }
  submissionList.value = []
  peerReviews.value = []
  showPeerReviews.value = false
}

// 获取提交状态列表
const fetchSubmissionStatus = async () => {
  try {
    const response = await axios.get(
      `/backend/api/assignment/${props.assignmentId}/submission_status/`,
      { withCredentials: true }
    )
    submissionList.value = response.data
  } catch (error) {
    console.error('获取提交状态失败:', error)
    ElMessage.error('获取提交状态失败，请稍后重试')
  }
}

// 查看学生提交的作业
const viewSubmission = async (submission) => {
  if (!submission || !submission.student_id) {
    ElMessage.warning('无法获取学生信息')
    return
  }

  try {
    const response = await axios.get(
      `/backend/api/assignment/${props.assignmentId}/submission/${submission.student_id}/`,
      { withCredentials: true }
    )
    currentSubmissionDetail.value = response.data
    gradingForm.value.teacher_score = response.data.grade || 0
  } catch (error) {
    console.error('获取作业详情失败:', error)
    ElMessage.error('获取作业详情失败，请稍后重试')
  }
}

// 获取互评记录
const fetchPeerReviews = async (submissionId) => {
  peerReviewsLoading.value = true
  try {
    const response = await axios.get(
      `/backend/api/assignment/submission/${submissionId}/peer_reviews/`,
      { withCredentials: true }
    )
    peerReviews.value = response.data
  } catch (error) {
    console.error('获取互评记录失败:', error)
    ElMessage.error('获取互评记录失败，请稍后重试')
  } finally {
    peerReviewsLoading.value = false
  }
}

// 查看互评记录
const viewPeerReviews = async (submission) => {
  if (!submission || !submission.submission_id) {
    ElMessage.warning('无法获取作业信息')
    return
  }
  currentSubmissionId.value = submission.submission_id
  showPeerReviews.value = true
  await fetchPeerReviews(submission.submission_id)
}

// 删除互评记录
const deletePeerReview = async (review) => {
  if (!review.score_id) {
    ElMessage.warning('无法获取评分记录信息')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除这条互评记录吗？', '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      type: 'warning'
    })

    await axios.delete(
      `/backend/api/assignment/peer_review/score/${review.score_id}/delete/`,
      { withCredentials: true }
    )

    ElMessage.success('删除成功')
    // 重新获取互评记录
      if (currentSubmissionId.value) {
      await fetchPeerReviews(currentSubmissionId.value)
    } else {
      ElMessage.warning('无法刷新互评记录，请重新打开互评列表')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除互评记录失败:', error)
      ElMessage.error('删除互评记录失败，请稍后重试')
    }
  }
}

// 提交评分
const submitGrade = async () => {
  if (!(currentSubmissionDetail.value && currentSubmissionDetail.value.id)) {
    ElMessage.warning('请先选择要评分的作业')
    return
  }

  // 检查互评是否截止
  const peerReviewDueDate = new Date(props.peerReviewDueDate)
  if (new Date() < peerReviewDueDate) {
    ElMessage.warning('互评尚未截止，请等待互评截止后再进行评分')
    return
  }

  try {
    await axios.post(
      `/backend/api/assignment/submission/${currentSubmissionDetail.value.id}/set_final_score/`,
      gradingForm.value,
      { withCredentials: true }
    )
    ElMessage.success('评分提交成功')
    await fetchSubmissionStatus()
    emit('graded')
  } catch (error) {
    console.error('提交评分失败:', error)
    ElMessage.error('提交评分失败，请稍后重试')
  }
}
// 处理学生选择
const handleStudentSelect = (row) => {
  if (row.status === 'SUBMITTED') {
    viewSubmission(row)
  } else {
    ElMessage.warning('该学生尚未提交作业')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).format(date)
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.grading-dialog :deep(.el-dialog__body) {
  padding: 0;
  height: calc(90vh - 100px);
  overflow: hidden;
}

.grading-container {
  display: flex;
  height: 100%;
  background: #f8fafc;
}

/* 左侧学生列表样式 */
.student-list {
  width: 45%;
  background: #fff;
  border-right: 1px solid #e2e8f0;
  display: flex;
  flex-direction: column;
  box-shadow: 4px 0 8px -4px rgba(0, 0, 0, 0.05);
}

.student-list :deep(.el-table) {
  flex: 1;
  overflow-y: auto;
  --el-table-header-bg-color: #f8fafc;
  --el-table-border-color: #e2e8f0;
}

.student-list :deep(.el-table__header) {
  position: sticky;
  top: 0;
  z-index: 2;
}

.student-list :deep(.el-table__row) {
  cursor: pointer;
  transition: background-color 0.2s;
}

.student-list :deep(.el-table__row:hover) {
  background-color: #f1f5f9;
}

.student-list :deep(.el-table__row.current-row) {
  background-color: #eff6ff;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  gap: 8px;
}

.operation-buttons :deep(.el-button--small) {
  padding: 6px 12px;
  border-radius: 4px;
}

/* 互评记录区域样式 */
.peer-reviews-section {
  padding: 20px;
  border-top: 1px solid #e2e8f0;
  background: #fff;
  height: 40%;
  overflow-y: auto;
}

.peer-reviews-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #1e293b;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.peer-reviews-section h4::before {
  content: '';
  width: 4px;
  height: 16px;
  background: #3b82f6;
  border-radius: 2px;
}

/* 右侧作业详情样式 */
.submission-detail {
  width: 55%;
  padding: 24px;
  overflow-y: auto;
  background: #fff;
}

.submission-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.submission-header h3 {
  margin: 0 0 12px 0;
  font-size: 20px;
  color: #1e293b;
  font-weight: 600;
}

.student-info {
  display: flex;
  gap: 24px;
  color: #64748b;
  font-size: 14px;
}

.student-info span {
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 作业内容区域样式 */
.submission-content h4 {
  margin: 24px 0 12px 0;
  font-size: 16px;
  color: #1e293b;
  font-weight: 600;
}

.content-text {
  background: #f8fafc;
  padding: 16px;
  border-radius: 8px;
  margin: 12px 0;
  white-space: pre-wrap;
  line-height: 1.6;
  color: #334155;
  border: 1px solid #e2e8f0;
}

/* 附件列表样式 */
.attachments {
  margin: 24px 0;
}

.attachments ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.attachments li {
  margin: 8px 0;
  padding: 8px 12px;
  background: #f8fafc;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.attachments :deep(.el-link) {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 评分区域样式 */
.grading-section {
  margin-top: 32px;
  padding: 24px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.grading-section :deep(.el-form-item) {
  margin-bottom: 20px;
}

.grading-section :deep(.el-form-item__label) {
  font-weight: 500;
  color: #334155;
}

.grading-section :deep(.el-input-number) {
  width: 160px;
}

/* 空状态样式 */
.no-selection {
  width: 55%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
  padding: 40px;
}

.no-selection :deep(.el-empty) {
  padding: 40px;
}

/* 评分展示样式 */
.score-display {
  display: flex;
  align-items: center;
  gap: 8px;
}

.score-display :deep(.el-rate) {
  margin-right: 8px;
}

/* 评价内容样式 */
.feedback-content {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #475569;
  font-size: 14px;
}

/* 无数据提示样式 */
.no-data {
  text-align: center;
  color: #94a3b8;
  padding: 32px;
  font-size: 14px;
  background: #f8fafc;
  border-radius: 8px;
  margin: 16px 0;
}

/* 状态标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  padding: 4px 8px;
}

/* 表格内链接样式 */
:deep(.el-link) {
  font-size: 14px;
}

/* 确保表格内按钮对齐 */
:deep(.el-table .cell) {
  white-space: nowrap;
}
</style>